package cn.smartinvoke;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import cn.smartinvoke.exception.InvokeException;
import cn.smartinvoke.util.HelpMethods;

public class ProtocolBuilder {
	private static Amf3Output amfOutPth=new Amf3Output();
	private static Amf3Input amfInput=new Amf3Input();
	static{
		TypeFactory.Object_Pool=ObjectPool.INSTANCE;
		TypeFactory.Type_Mapper=new TypeMapper();
	}
	public ProtocolBuilder() {
         
	}
	public static Object getObject(byte[] packBts) {
		Object ret = null;
		if (packBts != null) {
			ByteArrayInputStream in = new ByteArrayInputStream(packBts);
			amfInput.reset();
			amfInput.setInputStream(in);
			try {
				ret = amfInput.readObject();
				if (ret instanceof InvokeException) {
					throw (InvokeException) ret;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Throwable e) {
				e.printStackTrace();
				throw new InvokeException(HelpMethods.getThrowableInfo(e));
			}finally{
				try{in.close();}catch(Exception e){};
			}
		}
		return ret;
	}
	public static Object getObject(String pack,String appId) {
		Object ret = null;
		if (pack != null) {
			ByteArrayInputStream in = new ByteArrayInputStream(Base64
					.decode(pack.getBytes()));
			amfInput.reset();
			amfInput.setInputStream(in);
			
			try {
				ret = amfInput.readObject();
				if (ret instanceof InvokeException) {
					throw (InvokeException) ret;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Throwable e) {
				e.printStackTrace();
				throw new InvokeException(HelpMethods.getThrowableInfo(e));
			}finally{
				try{in.close();}catch(Exception e){};
			}
		}
		return ret;
	}
	public static byte[] getProtocolBts(Object obj) {
		byte[] ret = null;
		amfOutPth.reset();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		amfOutPth.setOutputStream(outStream);
		try {
			amfOutPth.setOutputStream(outStream);
			amfOutPth.writeObject(obj);
			outStream.flush();
			ret =outStream.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
		  try{outStream.close();}catch(Exception e){};
		}
		return ret;
	}
	public static String getProtocolStr(Object obj) {
		String ret = null;
		amfOutPth.reset();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		amfOutPth.setOutputStream(outStream);
		try {
			amfOutPth.setOutputStream(outStream);
			amfOutPth.writeObject(obj);
			outStream.flush();
			ret = new String(Base64.encode(outStream.toByteArray()));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
		  try{outStream.close();}catch(Exception e){};
		}
		return ret;
	}

	public static void main(String[] args) throws ClassNotFoundException {
		
	}
}